package com.uranus.common.bean.config;

import com.uranus.common.VO.Result;
import com.uranus.common.bean.expection.BusinessException;
import com.uranus.common.bean.expection.ParamsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.IOException;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionConfig {

    private Logger log = LoggerFactory.getLogger(getClass());
    @ExceptionHandler(ParamsException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleParamsException(ParamsException ex) {
        log.error("ParamsException:"+ex.getMessage(), ex);
        return Result.buildError(ex.getMessage()) ;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleBusinessException(BusinessException ex) {
        log.error("BusinessException:"+ex.getMessage(), ex);
        return Result.buildError(ex.getMessage()) ;
    }
    //栈溢出
    @ExceptionHandler({StackOverflowError.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result requestStackOverflow(StackOverflowError ex) {
        log.error("StackOverflowError:"+ex.getMessage(), ex);
        return Result.buildError("StackOverflowError:"+ ex.getMessage()) ;
    }
    //空指针异常
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result nullPointerExceptionHandler(NullPointerException ex) {
        log.error("NullPointerException:"+ex.getMessage(), ex);
        return Result.buildError("NullPointerException:" + ex.getMessage()) ;
    }
    //IO异常
    @ExceptionHandler(IOException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result iOExceptionHandler(IOException ex) {
        log.error("IOException:"+ex.getMessage(), ex);
        return Result.buildError("IOException:" + ex.getMessage()) ;
    }

    //运行时异常
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result runtimeExceptionHandler(RuntimeException ex) {
        log.error("RuntimeException:"+ex.getMessage(), ex);
        return Result.buildError("RuntimeException:"+ ex.getMessage()) ;
    }
    //其他错误
    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result exception(Exception ex) {
        log.error("Exception:"+ex.getMessage(), ex);
        return Result.buildError("Exception:"+ ex.getMessage()) ;
    }
}
